//
//  PreviewImageViewController.m
//  VinScanner
//
//  Created by Le Quang Vinh on 11/29/12.
//  Copyright (c) 2012 Le Quang Vinh. All rights reserved.
//

#import "PreviewImageViewController.h"
#import "Utilities.h"

@interface PreviewImageViewController ()

@end

@implementation PreviewImageViewController

@synthesize pictureImg          = _pictureImg;
@synthesize editPictureImgView  = _editPictureImgView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _editPictureImgView.image = _pictureImg;
    
    CGRect gripFrame = CGRectMake(30, 30, 260, 347);
    SPUserResizableView *userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:gripFrame];
    [contentView setBackgroundColor:[UIColor clearColor]];
    userResizableView.contentView = contentView;
    userResizableView.delegate = self;
    [userResizableView showEditingHandles];
    currentlyEditingView = userResizableView;
    lastEditedView = userResizableView;
    [self.view addSubview:userResizableView];
    [contentView release]; [userResizableView release];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)userResizableViewDidBeginEditing:(SPUserResizableView *)userResizableView {
    [currentlyEditingView hideEditingHandles];
    currentlyEditingView = userResizableView;
}

- (void)userResizableViewDidEndEditing:(SPUserResizableView *)userResizableView {
    lastEditedView = userResizableView;
    NSLog(@"New Frame crop : %@",[lastEditedView description]);
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([currentlyEditingView hitTest:[touch locationInView:currentlyEditingView] withEvent:nil]) {
        return NO;
    }
    return YES;
}

- (void)hideEditingHandles {
    // We only want the gesture recognizer to end the editing session on the last
    // edited view. We wouldn't want to dismiss an editing session in progress.
    [lastEditedView hideEditingHandles];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onRetake:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onCrop:(id)sender {
    
    // ImageView include view scan.
    UIImageView *imageView = [[UIImageView alloc] initWithImage:_pictureImg];
    // Size of image
    CGSize size = [_pictureImg size];
    // Rect need crop
    CGRect cropRect;
    cropRect.size.width = lastEditedView.frame.size.width;
    cropRect.size.height = lastEditedView.frame.size.height;
    // Crop image
    CGImageRef imageRef = CGImageCreateWithImageInRect([_pictureImg CGImage], cropRect);
    UIImage *cropImage = [self imageByCropping:_pictureImg toRect:lastEditedView.frame];
    CGImageRelease(imageRef);
    
    [_editPictureImgView setFrame:lastEditedView.frame];
    //img = [Utilities rotateImage:img byDegree:90];
    cropImage = [Utilities imageWithGrayScaleImage:cropImage];
    [_editPictureImgView setImage:img];
     
    // Way 2
    /*
    CGSize size = CGSizeMake(lastEditedView.frame.size.width, lastEditedView.frame.size.height);
    _pictureImg = [Utilities squareImageWithImage:_pictureImg scaledToSize:size];
    _editPictureImgView.frame = lastEditedView.frame;
    _editPictureImgView.image = cropImage;
     */
}

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    //create a context to do our clipping in
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    
    //create a rect with the size we want to crop the image to
    //the X and Y here are zero so we start at the beginning of our
    //newly created context
    
    CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
    
    CGContextClipToRect( currentContext, clippedRect);
    
    //create a rect equivalent to the full size of the image
    //offset the rect by the X and Y we want to start the crop
    //from in order to cut off anything before them
    
    CGRect drawRect = CGRectMake(rect.origin.x * -1,
                                 rect.origin.y * -1,
                                 imageToCrop.size.width,
                                 imageToCrop.size.height);
    
    //draw the image to our clipped context using our offset rect
    
    CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
    
    //pull the image from our cropped context
    
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
    
    //pop the context to get back to the default
    
    UIGraphicsEndImageContext();
    
    //Note: this is autoreleased
    
    return cropped;

}


@end
